export function param2Obj(url) {
    const search = url.split('?')[1]
    if (!search) {
      return {}
    }
    return JSON.parse(
      '{"' +
        decodeURIComponent(search)
          .replace(/"/g, '\\"')
          .replace(/&/g, '","')
          .replace(/=/g, '":"') +
        '"}'
    )
}

export function formatRes(data, isError = false) {
  if (!isError) {
    return {
      code: 200,
      data: data,
      msg: '成功'
    }
  } else {
    return {
      code: -101,
      data: data,
      msg: '错误'
    }
  }
}
// 判断值是不是null
const isNull = (value) => {
  if (value === null || value === undefined) return true;
  return false;
};

// 判断变量是否是null 和空字符串
const isEmpty = (value) => {
  if (isNull(value)) return true;
  if (value === '') return true;
  return false;
};

// 判断对象的数据类型 Null Undefined Object Array
const isClass = (o) => {
  if (o === null) return 'Null';
  if (o === undefined) return 'Undefined';
  return Object.prototype.toString.call(o).slice(8, -1);
};

// 判断是否是日期
const isDate = (date) => {
  if (isNull(date)) return false;
  return date instanceof Date;
};

const isFunction = obj => (typeof obj === 'function' && typeof obj.nodeType !== 'number');

// 深度拷贝一个对象
const deepClone = (obj) => {
  let result;
  const oClass = isClass(obj);
  if (oClass === 'Object') {
    result = {};
  } else if (oClass === 'Array') {
    result = [];
  } else {
    return obj;
  }
  for (const key in obj) { // eslint-disable-line
    const copy = obj[key];
    if (isClass(copy) === 'Object') {
      result[key] = deepClone(copy);// 递归调用
    } else if (isClass(copy) === 'Array') {
      result[key] = deepClone(copy);
    } else {
      result[key] = obj[key];
    }
  }
  return result;
};
export function isExternal(path) {
  return /^(https?:|mailto:|tel:)/.test(path)
}
// 通过A标签去解析url
const parseURL = (url) => {
  const a = document.createElement('a');
  a.href = url;
  return {
    source: url,
    protocol: a.protocol.replace(':', ''),
    host: a.hostname,
    port: a.port || '80',
    query: a.search,
    params: (() => {
      const ret = {};
      const seg = a.search.replace(/^\?/, '').split('&');
      const len = seg.length;
      let i = 0;
      let s;
      for (; i < len; i += 1) {
        if (seg[i]) {
          s = seg[i].split('=');
          ret[s[0]] = s[1];
        }
      }
      return ret;
    })(),
    file: (a.pathname.match(/\/([^\/?#]+)$/i) || [, ''])[1],// eslint-disable-line
    hash: a.hash.replace('#', ''),
    path: a.pathname.replace(/^([^\/])/, '/$1'),// eslint-disable-line
    relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [, ''])[1],// eslint-disable-line
    segments: a.pathname.replace(/^\//, '').split('/'),
  };
};

export default {
  isNull,
  param2Obj,
  isClass,
  isDate,
  isFunction,
  parseURL,
  deepClone,
  formatRes
}